package com.nexgo.payment.trans.download;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.nexgo.common.ByteUtils;
import com.nexgo.data.entity.RecvData;
import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.aop.annotation.RunOnWorkThread;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.databases.QpsBinC;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.trans.AbsOnlinePresenter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by xiaox on 2017/8/12.
 */
public class QpsBinCPresenter extends AbsOnlinePresenter implements DownloadTransContract.Presenter {
    private Logger mLog = LoggerFactory.getLogger(QpsBinCPresenter.class.getSimpleName());

    private DownloadTransContract.View mView;

    protected QpsBinCPresenter(@NonNull DownloadTransContract.View view, @NonNull DataSource repository) {
        super(view, repository);
        mView = checkNotNull(view);
    }

    @Override
    protected TransData getTransData() {
        TransData transData = new TransData();
        transData.setTransType(TransType.QPS_BIN_C_DOWN);
        return transData;
    }

    @Override
    protected void onFirstAction() {
        mRepository.setParamValue(PreferencesConstants.QPS_BIN_C_INIT_FLAG, "1");
        mRepository.syncParamValue();
        postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.qps_blacklist_down)));
    }

    @Override
    @RunOnWorkThread
    protected void onTransSuccess(RecvData recvData) {
        if (TransType.QPS_BIN_C_DOWN.equals(mTransData.getTransType())) {
            if (TextUtils.isEmpty(recvData.getField62())) {
                postMainThread(() -> mView.showTransFailed());
                return;
            }
            int offset = 0;
            String data = new String(ByteUtils.hexString2ByteArray(recvData.getField62()));
            if (data.startsWith("0") || data.length() <= 1) {
                //无卡bin，或是错误
                mTransData.setTransType(TransType.QPS_BIN_C_END);
                postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.qps_blacklist_end)));
                return;
            }
            mLog.debug("免密卡BIN黑名单返回值：{}", data);
            try {
                offset++;
                Integer lastItem = Integer.parseInt(data.substring(offset, offset + 3));
                offset += 3;
                if (mTransData.getCounter() == 0) {
                    //第一次下载删除所有的卡bin
                    mRepository.clearQpsBinC();
                }
                postMainThread(() -> mView.setWaitingIndicator(true, null, App.sContext.getString(R.string.doing_something)));
                for (int i = 0; i < lastItem - mTransData.getCounter() + 1; i++) {
                    String bin = data.substring(offset, offset + 8);
                    mLog.debug("Bin : {}", bin);
                    offset += 8;
                    QpsBinC qpsBinC = new QpsBinC();
                    qpsBinC.setCardBin(bin);
                    mRepository.insertQpsBinC(qpsBinC);
                }
                postMainThread(() -> mView.setWaitingIndicator(false, null, null));
                if (data.startsWith("1") || lastItem < mTransData.getCounter()) {
                    //无后续
                    mTransData.setTransType(TransType.QPS_BIN_C_END);
                    postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.qps_blacklist_end)));
                } else {
                    mTransData.setCounter(lastItem + 1);
                    postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.qps_blacklist_down)));
                }
            }catch (Exception e){
                e.printStackTrace();
                postMainThread(() -> mView.setWaitingIndicator(false, null, null));
                postMainThread(() -> mView.showTransFailed());
            }
        } else {
            postMainThread(() -> mView.showTransSuccess());
        }
    }
}
